<template>
	<view class="info-pages">
		<!-- 使用keep-alive缓存组件状态 -->
		<keep-alive>
			<view class="info-block">
				<view class="title" v-once>请确认缴费信息</view>

				<!-- 使用计算属性优化模板渲染 -->
				<view class="info-item">
					<view class="info-title">地址</view>
					<view class="info-text">{{formattedAddress}}</view>
				</view>

				<view class="info-item">
					<view class="info-title">房租到期时间</view>
					<view class="info-text">{{info.endTime}}到期</view>
				</view>

				<view class="info-item">
					<view class="info-title">续费时段</view>
					<view class="info-text">{{formattedTimeRange}}</view>
				</view>

				<view class="info-item">
					<view class="info-title">缴费金额</view>
					<view class="info-text red">{{info.price}}元</view>
				</view>

				<view class="info-item">
					<view class="info-title">下次到期时间</view>
					<view class="info-text">{{info.lastTime}}到期</view>
				</view>
			</view>
		</keep-alive>

		<!-- 添加加载状态防止重复点击 -->
		<view class="btn normal" @click="handleSubmit" :disabled="isPaying">
			{{isPaying ? '支付中...' : `￥${info.price} 确认缴费`}}
		</view>

		<!-- 发票申请使用v-show优化频繁切换 -->
		<view class="invoice" v-show="showInvoice" @click="applyInvoice">
			若开具发票，点击申请
		</view>

		<!-- 支付结果提示 -->
		<uni-popup ref="popup" type="message">
			<uni-popup-message :type="msgType" :message="message" />
		</uni-popup>
	</view>
</template>

<script>
	import {
		validate
	} from '@/util/validate.js';
	import {
		getStorage
	} from '@/util/auth.js';
	import moment from 'moment';
	import {
		payment
	} from '@/api/payment.js';
	import {
		debounce
	} from 'lodash';
	export default {
		data() {
			return {
				isPaying: false, // 支付状态
				showInvoice: true, // 发票显示状态
				msgType: '', // 消息类型
				message: '', // 消息内容
				selectInfo: {}, // 选择信息
				info: {
					address: '',
					endTime: '',
					time: '',
					price: 0,
					month: 0,
					lastTime: '',
					payableRent: 0
				}
			};
		},
		computed: {
			// 格式化地址
			formattedAddress() {
				return [
					this.selectInfo?.areaName,
					this.selectInfo?.streetName,
					this.selectInfo?.buildingNumber,
					this.selectInfo?.unitNumber && `#${this.selectInfo.unitNumber}`,
					this.selectInfo?.floorLevel && `-${this.selectInfo.floorLevel}`,
					this.selectInfo?.roomNumber
				].filter(Boolean).join('');
			},
			// 格式化时间范围
			formattedTimeRange() {
				return `${this.info.endTime}至${this.info.lastTime}(${this.info.month}个月)`;
			},
			// 计算面积
			calculatedArea() {
				return this.selectInfo.houseType?.includes('廉租') ||
					this.selectInfo.houseType?.includes('公租') ?
					this.selectInfo.susableArea :
					this.selectInfo.buildingArea;
			}
		},
		methods: {
			// 防抖处理提交
			handleSubmit: debounce(function() {
				this.submit();
			}, 500),

			// 提交支付
			async submit() {
				if (this.isPaying) return;

				try {
					this.isPaying = true;

					const data = {
						idValue: this.selectInfo.idValue,
						type: 2,
						beforeAdjustment: this.selectInfo.unitPricePerSquare,
						afterAdjustment: this.selectInfo.calculatedPrice,
						calculatedArea: this.calculatedArea,
						payableRent: this.info.payableRent,
						rent: 0.01, // 测试金额
						rentMonth: this.info.month,
					};
					const res = await this.handlePayment(data);

					if (!res) {
						this.showToast('支付失败，请联系管理员');
						return;
					}

					await this.handleWxPayment(res);

				} catch (error) {
					console.error('支付错误:', error);
					this.showToast('支付失败，请联系管理员');
				} finally {
					this.isPaying = false;
				}
			},

			// 处理支付请求
			async handlePayment(data) {
				try {
					const res = await payment(data);
					return res;
				} catch (error) {
					console.error('支付请求错误:', error);
					throw error;
				}
			},

			// 处理微信支付
			handleWxPayment(res) {
				return new Promise((resolve, reject) => {
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.timeStamp,
						nonceStr: res.nonceStr,
						package: res.package,
						signType: 'MD5',
						paySign: res.paySign,
						success: () => {
							this.showToast('缴纳成功');
							setTimeout(() => {
								uni.redirectTo({
									url: `/page_pack/pay_success/rent_success?price=${this.info.price}&month=${this.info.month}`
								});
							}, 1500);
							resolve();
						},
						fail: (err) => {
							console.error('支付失败:', err);
							let msg = '支付失败，请联系管理员';
							if (err.errMsg.includes('cancel')) {
								msg = '您已取消支付';
							}
							this.showToast(msg);
							reject(err);
						}
					});
				});
			},

			// 显示消息提示
			showMessage(message, type = 'success') {
				this.message = message;
				this.msgType = type;
				this.$refs.popup.open();
			},

			// 申请发票
			applyInvoice() {
				uni.navigateTo({
					url: '/pages/invoice/apply'
				});
			},

			// 格式化日期
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			}
		},
		onLoad(e) {
			console.log(e)
			this.info.price = e.price;
			this.info.month = e.month;
			this.info.payableRent = e.payableRent
		},
		onShow() {
			try {
				// 获取缓存数据
				this.selectInfo = getStorage('selectInfo');
				this.info.endTime = this.selectInfo.expirationDate;
				this.info.lastTime = this.formatDate(
					moment(this.info.endTime).add(this.info.month, 'months').toDate()
				);

				// 使用计算属性替代模板中的复杂表达式
				// this.info.address = this.formattedAddress;
				// this.info.time = this.formattedTimeRange;

			} catch (error) {
				console.error('页面初始化错误:', error);
				this.showToast('数据加载失败');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.info-pages {
		padding: 30rpx;

		.info-block {
			padding: 30rpx;
			background-color: #fff;
			border-radius: 30rpx;

			.red {
				color: $theme-color;
				font-weight: bold;
			}

			.title {
				font-size: 34rpx;
				font-weight: bold;
			}

			.info-item:last-child {
				border-bottom: none;
			}

			.info-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				line-height: 90rpx;
				border-bottom: 1px solid #f7f7f7;

				.info-title {
					font-size: 28rpx;
					color: #767676;
				}

				.info-text {
					font-size: 28rpx;
				}
			}
		}

		.btn {
			border-radius: 20rpx;
			margin-top: 40rpx;
		}

		.invoice {
			position: absolute;
			color: $theme-color;
			font-size: 28rpx;
			bottom: 30rpx;
			left: 30%;
		}
	}
</style>